package com.example.myapplication.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.myapplication.R;
import com.example.myapplication.bean.User;
import com.example.myapplication.utils.OkHttpUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private Toolbar toolbar;
    private EditText etPhone;
    private EditText etPassword;
    private String phone;
    private String password;
    private Context context = LoginActivity.this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    private void init() {
        etPhone = findViewById(R.id.et_phone_login);
        etPassword = findViewById(R.id.et_password_login);
        toolbar = findViewById(R.id.tb_login);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }


    public void login(View view) {
        if (canLogin()) {
            final User user = new User();
            user.setPhone(phone);
            user.setPassword(password);
            new Thread(){
                @Override
                public void run() {
                    sendLoginReq(user);
                }
            }.start();
        }
    }

    public void toRegister(View view) {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    private boolean canLogin() {
        String userphone = etPhone.getText().toString();
        String userpassword = etPassword.getText().toString();

        if (!userphone.isEmpty()) {
            if (!userpassword.isEmpty()) {
                phone = userphone;
                password = userpassword;
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public void sendLoginReq(User user) {
        JSONObject post = OkHttpUtil.post(user,  "/user/login");
        Gson gson = new Gson();
        final User user1 = gson.fromJson(post.toString(), User.class);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                user1.toastMassage(context);
            }
        });
        if (user1.isSuccess()) {
            startActivity(new Intent(this, TeamsActivity.class));
        }
    }
}